<template>
  <div class="app-container">
    <el-tabs v-model="activeTab" type="border-card">
      <el-tab-pane label="收款码管理" name="qrcode">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span>收款码设置</span>
              <el-button type="primary" @click="handleSaveQrCode">保存</el-button>
            </div>
          </template>
          <el-form ref="qrcodeFormRef" :model="qrcodeForm" label-width="120px" :rules="qrcodeRules">
            <el-form-item label="支付宝收款码" prop="alipayPicQrcode">
              <SingleImageUpload v-model="qrcodeForm.alipayPicQrcode" />
            </el-form-item>
            <el-form-item label="微信收款码" prop="wxPicQrcode">
              <SingleImageUpload v-model="qrcodeForm.wxPicQrcode" />
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>
      
      <el-tab-pane label="代理返佣管理" name="discount">
        <div class="search-bar">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="返佣名称">
              <el-input v-model="queryParams.name" placeholder="请输入返佣名称" clearable style="width: 200px" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery" v-if="hasAuth(['genealogy:custom-price-discount:query'])">
                <template #icon><Search /></template>
                搜索
              </el-button>
              <el-button @click="handleResetQuery" v-if="hasAuth(['genealogy:custom-price-discount:query'])">
                <template #icon><Refresh /></template>
                重置
              </el-button>
              <el-button type="success" @click="handleAdd" v-if="hasAuth(['genealogy:custom-price-discount:add'])">
                <template #icon><Plus /></template>
                新增
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never">
          <el-table
            ref="dataTableRef"
            v-loading="loading"
            :data="pageData"
            highlight-current-row
            border
          >
            <el-table-column key="id" label="ID" prop="id" min-width="80" align="center" />
            <el-table-column key="name" label="返佣名称" prop="name" min-width="150" align="center" />
            <el-table-column key="discount" label="返佣比例" prop="discount" min-width="120" align="center">
              <template #default="scope">
                {{ `${scope.row.discount}%` }}
              </template>
            </el-table-column>
            <el-table-column key="packageId" label="商品名称" prop="packageName" min-width="150" align="center" />
            <el-table-column key="userId" label="会员名称" prop="userName" min-width="120" align="center" />
            <el-table-column key="agentType" label="代理类型" min-width="120" align="center">
              <template #default="scope">
                {{ getAgentTypeLabel(scope.row.agentType) }}
              </template>
            </el-table-column>
            <el-table-column key="createTime" label="创建时间" prop="createTime" min-width="160" align="center" />
            <el-table-column key="updateTime" label="更新时间" prop="updateTime" min-width="160" align="center" />
            <el-table-column fixed="right" label="操作" width="180" v-if="hasAuth(['genealogy:custom-price-discount:edit', 'genealogy:custom-price-discount:delete'])">
              <template #default="scope">
                <el-button type="primary" size="small" link @click="handleEdit(scope.row)" v-if="hasAuth(['genealogy:custom-price-discount:edit'])">编辑</el-button>
                <el-button type="danger" size="small" link @click="handleDelete(scope.row)" v-if="hasAuth(['genealogy:custom-price-discount:delete'])">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery()"
          />
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 代理返佣表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="form.id ? '编辑返佣设置' : '新增返佣设置'" width="500px">
      <el-form ref="formRef" :model="form" label-width="120px" :rules="rules">
        <el-form-item label="会员" prop="userId">
          <div class="member-select">
            <div v-if="form.userId" class="selected-user">
              <span>{{ selectedUserName }}</span>
              <span v-if="selectedUserMobile" class="user-mobile">{{ selectedUserMobile }}</span>
              <el-button link type="primary" @click="clearSelectedUser">
                <el-icon><Close /></el-icon>
              </el-button>
            </div>
            <el-button v-else type="primary" @click="openUserSelectDialog" plain>选择会员</el-button>
          </div>
        </el-form-item>
        <el-form-item label="代理类型" prop="agentType">
          <el-select v-model="form.agentType" placeholder="请选择代理类型" style="width: 100%" @change="handleAgentTypeChange">
            <el-option 
              v-for="type in agentTypeOptions" 
              :key="type.value" 
              :label="type.label" 
              :value="type.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="返佣名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入返佣名称" />
        </el-form-item>
        <el-form-item label="返佣比例" prop="discount">
          <el-input-number v-model="form.discount" :min="0" :max="100" :precision="2" :step="5" style="width: 100%">
            <template #suffix>%</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="商品" prop="packageId">
          <el-select v-model="form.packageId" placeholder="请选择商品" style="width: 100%">
            <el-option 
              v-for="pkg in packageOptions" 
              :key="pkg.id" 
              :label="pkg.packageName" 
              :value="pkg.id" 
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="删除确认" width="300px">
      <span>确定要删除该返佣设置吗？</span>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定</el-button>
      </template>
    </el-dialog>

    <!-- 会员选择对话框 -->
    <el-dialog v-model="userSelectDialogVisible" title="选择会员" width="1000px">
      <div class="search-bar">
        <el-form :inline="true">
          <el-form-item label="关键词">
            <el-input 
              v-model="userSearchParams.keywords" 
              placeholder="请输入用户名/昵称/手机号" 
              clearable 
              @keyup.enter="searchUsers"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchUsers">
              <template #icon><Search /></template>
              搜索
            </el-button>
            <el-button @click="resetUserSearch">
              <template #icon><Refresh /></template>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <el-table
        v-loading="userTableLoading"
        :data="userTableData"
        border
        height="400px"
        highlight-current-row
        @row-click="handleUserRowClick"
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="nickname" label="昵称" min-width="120" />
        <el-table-column prop="mobile" label="手机号" min-width="120" />
        <el-table-column prop="mergerName" label="区域" min-width="200" />
        <el-table-column prop="levelName" label="等级" min-width="100" />
        <el-table-column fixed="right" label="操作" width="80">
          <template #default="scope">
            <el-button type="primary" link @click.stop="selectUser(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <pagination
          v-if="userTotal > 0"
          v-model:total="userTotal"
          v-model:page="userSearchParams.pageNum"
          v-model:limit="userSearchParams.pageSize"
          @pagination="searchUsers"
        />
      </div>
      
      <template #footer>
        <el-button @click="userSelectDialogVisible = false">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import PaymentAPI from "@/api/genealogy/payment.api";
import PriceDiscountAPI from "@/api/genealogy/price-discount.api";
import PackageAPI from "@/api/genealogy/package.api";
import FamilyUserAPI from "@/api/genealogy/family-user.api";
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Refresh, Plus, Close } from '@element-plus/icons-vue';
import SingleImageUpload from "@/components/Upload/SingleImageUpload.vue";
import { hasAuth } from "@/plugins/permission";
import { useUserStore } from "@/store";

// 从用户存储中获取用户信息
const userStore = useUserStore();
const { areaCodeBelong, baseFlag } = userStore.userInfo;

// 标签页
const activeTab = ref('qrcode');

// 收款码表单
const qrcodeFormRef = ref();
const qrcodeForm = reactive({
  alipayPicQrcode: '',
  wxPicQrcode: ''
});

const qrcodeRules = {
  alipayPicQrcode: [{ required: true, message: '请上传支付宝收款码', trigger: 'change' }],
  wxPicQrcode: [{ required: true, message: '请上传微信收款码', trigger: 'change' }]
};

// 表格数据
const loading = ref(false);
const total = ref(0);
const pageData = ref([]);
const packageOptions = ref([]);
const userOptions = ref([]); // 用户选项

// 查询参数
const queryFormRef = ref();
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: undefined
});

// 表单相关
const dialogVisible = ref(false);
const formRef = ref();
const form = reactive({
  id: undefined,
  name: '',
  discount: 0,
  packageId: undefined,
  userId: undefined, // 会员ID
  agentType: undefined // 代理类型
});

// 代理类型选项
const agentTypeOptions = [
  { label: '经理', value: 'level1' },
  { label: '业务员', value: 'level2' }
];

// 表单校验规则
const rules = {
  name: [{ required: true, message: '请输入返佣名称', trigger: 'blur' }],
  discount: [{ required: true, message: '请输入返佣比例', trigger: 'blur' }],
  packageId: [{ required: true, message: '请选择商品', trigger: 'change' }],
  userId: [{ required: true, message: '请选择会员', trigger: 'change' }],
  agentType: [{ required: true, message: '请选择代理类型', trigger: 'change' }]
};

// 删除相关
const deleteDialogVisible = ref(false);
const currentDeleteId = ref<number | string>();

// 会员选择相关
const userSelectDialogVisible = ref(false);
const userTableLoading = ref(false);
const userTableData = ref([]);
const userTotal = ref(0);
const userSearchParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keywords: ''
});

// 计算已选择会员的显示信息
const selectedUserName = computed(() => {
  if (!form.userId) return '';
  const user = userOptions.value.find(u => u.id === form.userId);
  return user ? (user.nickname || user.username) : '';
});

const selectedUserMobile = computed(() => {
  if (!form.userId) return '';
  const user = userOptions.value.find(u => u.id === form.userId);
  return user ? user.mobile : '';
});

// 初始化
onMounted(() => {
  getQrCodeInfo();
  
  if (hasAuth(['genealogy:custom-price-discount:query'])) {
    loadPackageOptions();
    loadUserOptions(); // 加载会员选项
    handleQuery();
  }
});

// 获取收款码信息
function getQrCodeInfo() {
  loading.value = true;
  PaymentAPI.getPaymentQrCode()
    .then((data: any) => {
      qrcodeForm.alipayPicQrcode = data.alipayPicQrcode || '';
      qrcodeForm.wxPicQrcode = data.wxPicQrcode || '';
    })
    .finally(() => {
      loading.value = false;
    });
}

// 保存收款码
function handleSaveQrCode() {
  qrcodeFormRef.value?.validate((valid: boolean) => {
    if (!valid) return;
    loading.value = true;
    PaymentAPI.updatePaymentQrCode(qrcodeForm)
      .then(() => {
        ElMessage.success('保存成功');
      })
      .catch(() => {
        ElMessage.error('保存失败');
      })
      .finally(() => {
        loading.value = false;
      });
  });
}

// 加载商品选项
const loadPackageOptions = async () => {
  try {
    const res = await PackageAPI.getPage({ pageNum: 1, pageSize: 100 });
    packageOptions.value = res.list || [];
  } catch (error) {
    console.error('加载商品选项失败', error);
  }
};

// 加载会员选项
const loadUserOptions = async () => {
  try {
    // 根据当前用户的区域范围筛选会员
    const userParams = {
      pageNum: 1,
      pageSize: 100
    };
    
    const res = await FamilyUserAPI.getMembersPage(userParams);
    userOptions.value = res.list || [];
  } catch (error) {
    console.error('加载会员选项失败', error);
  }
};

// 获取代理类型名称
const getAgentTypeLabel = (type) => {
  const option = agentTypeOptions.find(opt => opt.value === type);
  return option ? option.label : '-';
};

// 查询列表
const handleQuery = async () => {
  if (!hasAuth(['genealogy:custom-price-discount:query'])) {
    ElMessage.warning('您没有查询权限');
    return;
  }
  
  loading.value = true;
  try {
    const res = await PriceDiscountAPI.getPage(queryParams);
    pageData.value = res.list || [];
    
    // 处理商品名称显示和用户名称显示
    for (const item of pageData.value) {
      if (item.packageId) {
        const packageInfo = packageOptions.value.find(pkg => pkg.id === item.packageId);
        if (packageInfo) {
          item.packageName = packageInfo.packageName;
        } else {
          // 如果在现有选项中找不到，直接显示为"-"
          item.packageName = '-';
        }
      } else {
        item.packageName = '-';
      }
      
      // 处理用户名称显示
      if (item.userId) {
        const userInfo = userOptions.value.find(user => user.id === item.userId);
        if (userInfo) {
          item.userName = userInfo.nickname || userInfo.username;
        } else {
          item.userName = '-';
        }
      } else {
        item.userName = '-';
      }
    }
    
    total.value = res.total || 0;
  } catch (error) {
    console.error('查询返佣列表失败', error);
    ElMessage.error('查询返佣列表失败');
  } finally {
    loading.value = false;
  }
};

// 重置查询
const handleResetQuery = () => {
  if (!hasAuth(['genealogy:custom-price-discount:query'])) {
    ElMessage.warning('您没有查询权限');
    return;
  }
  
  queryFormRef.value?.resetFields();
  handleQuery();
};

// 新增
const handleAdd = () => {
  if (!hasAuth(['genealogy:custom-price-discount:add'])) {
    ElMessage.warning('您没有新增权限');
    return;
  }
  
  resetForm();
  dialogVisible.value = true;
};

// 编辑
const handleEdit = async (row) => {
  if (!hasAuth(['genealogy:custom-price-discount:edit'])) {
    ElMessage.warning('您没有编辑权限');
    return;
  }
  
  resetForm();
  try {
    const formData = await PriceDiscountAPI.getFormData(row.id);
    Object.assign(form, formData);
    
    // 如果有会员ID，加载会员信息
    if (form.userId && !userOptions.value.find(user => user.id === form.userId)) {
      try {
        const userInfo = await FamilyUserAPI.getFormData(form.userId);
        if (userInfo && !userOptions.value.some(user => user.id === userInfo.id)) {
          userOptions.value.push(userInfo);
        }
      } catch (error) {
        console.error('获取会员信息失败', error);
      }
    }
    
    dialogVisible.value = true;
  } catch (error) {
    console.error('获取表单数据失败', error);
    ElMessage.error('获取表单数据失败');
  }
};

// 删除
const handleDelete = (row) => {
  if (!hasAuth(['genealogy:custom-price-discount:delete'])) {
    ElMessage.warning('您没有删除权限');
    return;
  }
  
  currentDeleteId.value = row.id;
  deleteDialogVisible.value = true;
};

// 确认删除
const confirmDelete = async () => {
  if (!currentDeleteId.value) return;
  
  if (!hasAuth(['genealogy:custom-price-discount:delete'])) {
    ElMessage.warning('您没有删除权限');
    return;
  }
  
  try {
    await PriceDiscountAPI.deleteByIds(currentDeleteId.value);
    ElMessage.success('删除成功');
    handleQuery();
  } catch (error) {
    console.error('删除返佣设置失败', error);
    ElMessage.error('删除返佣设置失败');
  } finally {
    deleteDialogVisible.value = false;
    currentDeleteId.value = undefined;
  }
};

// 重置表单
const resetForm = () => {
  form.id = undefined;
  form.name = '';
  form.discount = 0;
  form.packageId = undefined;
  form.userId = undefined;
  form.agentType = undefined;
};

// 提交表单
const submitForm = async () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return;
    
    // 检查权限
    const permissionKey = form.id ? 'genealogy:custom-price-discount:edit' : 'genealogy:custom-price-discount:add';
    if (!hasAuth([permissionKey])) {
      ElMessage.warning(`您没有${form.id ? '编辑' : '新增'}权限`);
      return;
    }
    
    try {
      // 准备提交的数据
      const submitData = { ...form };
      
      if (form.id) {
        // 编辑
        await PriceDiscountAPI.update(form.id, submitData);
      } else {
        // 新增
        await PriceDiscountAPI.create(submitData);
      }
      
      ElMessage.success(form.id ? '编辑成功' : '新增成功');
      dialogVisible.value = false;
      handleQuery();
    } catch (error) {
      console.error(form.id ? '编辑返佣设置失败' : '新增返佣设置失败', error);
      ElMessage.error(form.id ? '编辑返佣设置失败' : '新增返佣设置失败');
    }
  });
};

// 监听代理类型变化
const handleAgentTypeChange = (value) => {
  if (!value) return;
};

// 处理用户选择变化
const handleUserChange = (userId) => {
  if (!userId) return;
  
  const selectedUser = userOptions.value.find(user => user.id === userId);
  if (!selectedUser) return;
  
  // 根据用户的区域和等级设置可选的代理类型
  if (selectedUser.areaCodeScope === 6) {
    // 如果用户是普通会员，默认设置为一级代理
    form.agentType = 'level1';
  } else {
    // 其他情况，可能是二级代理
    form.agentType = 'level2';
  }
};

// 打开会员选择对话框
const openUserSelectDialog = () => {
  userSearchParams.pageNum = 1;
  userSearchParams.keywords = '';
  userSelectDialogVisible.value = true;
  searchUsers();
};

// 搜索会员
const searchUsers = async () => {
  userTableLoading.value = true;
  try {
    const res = await FamilyUserAPI.getMembersPage(userSearchParams);
    userTableData.value = res.list || [];
    userTotal.value = res.total || 0;
  } catch (error) {
    console.error('搜索会员失败', error);
    ElMessage.error('搜索会员失败');
  } finally {
    userTableLoading.value = false;
  }
};

// 重置会员搜索
const resetUserSearch = () => {
  userSearchParams.keywords = '';
  userSearchParams.pageNum = 1;
  searchUsers();
};

// 点击会员行
const handleUserRowClick = (row) => {
  selectUser(row);
};

// 选择会员
const selectUser = (user) => {
  // 更新表单中的会员ID
  form.userId = user.id;
  
  // 确保已选会员在选项列表中，如果不在则添加
  if (!userOptions.value.some(u => u.id === user.id)) {
    userOptions.value.push(user);
  }
  
  // 根据会员的区域和等级设置代理类型
  handleUserChange(user.id);
  
  // 关闭对话框
  userSelectDialogVisible.value = false;
};

// 清除已选会员
const clearSelectedUser = () => {
  form.userId = undefined;
};
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
}

.member-select {
  width: 100%;
}

.selected-user {
  display: flex;
  align-items: center;
  padding: 5px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.user-mobile {
  margin-left: 10px;
  font-size: 12px;
  color: #909399;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}
</style> 